<template>
	<view class="baseForm">
		<view class="overhidden">
			<view>
				<!-- 条码录入 -->
				<view class="searchScan_div">
					<scan-bar ref="scanBarRef" placeholder="请扫描或输入耗材编号" @code-scanned="getScanResult" :key="datekey"></scan-bar>
				</view>

				<u--form labelPosition="top" :model="formData" :rules="rules" labelWidth="300" ref="uForm" class="form common_form" errorType="toast">
					<view v-show="!taskInfo?.consumeCode && loading === false" class="flex justify-center font-14" style="margin: 30px 0 30px 0">暂无耗材信息，请录入耗材编号</view>
					<u-loading-icon class="flex justify-center mt-20" textSize="18" v-show="loading"></u-loading-icon>
					<!-- 耗材详情 -->
					<ConsumablesDetachInfo v-if="taskInfo?.consumeCode" :taskInfo="taskInfo"></ConsumablesDetachInfo>
					<!-- 拆卸状态选择 -->
					<view class="plan card record-content" v-if="taskInfo?.consumeCode">
						<u-form-item label="拆卸状态" prop="detachStatus" required>
							<u-radio-group v-model="formData.detachStatus">
								<u-radio
									:customStyle="{ marginRight: '30px', fontSize: '14px' }"
									shape="square"
									v-for="(item, index) in useDictionaryStore().filterDictList('csmDetachStatus')"
									:key="index"
									:label="item.label"
									:name="item.value"
								></u-radio>
							</u-radio-group>
						</u-form-item>
					</view>
					<!-- 具体耗材选择 -->
					<uni-table
						v-if="taskInfo?.consumeCode"
						ref="tableRef"
						stripe
						type="selection"
						selection-key="id"
						emptyText="暂无数据"
						@selection-change="selectionChange"
						class="unitable"
					>
						<uni-tr>
							<uni-th width="90" align="center">耗材序列号</uni-th>
							<uni-th width="75" align="center">累计寿命</uni-th>
							<uni-th width="80" align="center">本次消耗</uni-th>
						</uni-tr>
						<uni-tr v-for="(item, index) in taskInfo.list" :key="index">
							<uni-td align="center">{{ index + 1 }}</uni-td>
							<uni-td align="center">{{ item.workLife }}</uni-td>
							<uni-td align="center">{{ (item.workLife - item.lastWorkLife).toFixed((2)) }}</uni-td>
						</uni-tr>
					</uni-table>

					<!-- 提交 -->
					<view class="submit_btn_div">
						<button type="default" class="grey_btn" @click="resetFields">重 置</button>
						<button type="primary" :disabled="postLoading" :loading="postLoading" @click="submit" class="submit_btn">提 交</button>
					</view>
				</u--form>
			</view>
		</view>
		<u-back-top :scroll-top="scrollTop" top="200" mode="squery"></u-back-top>
	</view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { onPageScroll, onShow } from '@dcloudio/uni-app';
import ConsumablesDetachInfo from '@/pages/eam/consumables/detach/components/info.vue';
import { http } from '@/utils/http';
import { mockData } from './index';
import { useDictionaryStore } from '@/stores/useDictionaryStore';
import ScanBar from '@/components/scan-bar/index.vue';

// 监听页面到顶部距离
const scrollTop = ref(0);
//列表高度
onPageScroll((e) => {
	scrollTop.value = e.scrollTop;
});

// 表单详情
let formData = reactive({
	consumeCode: '',
	detachStatus: null,
	detachIndexs: [],
	detachIds: []
});

// 初始化页面，获取检查详情
let taskInfo = ref<any>({});
const loading = ref(false);

// 多选
function selectionChange(e) {
	formData.detachIndexs = e.detail.index;
	if (e.detail.index.length) {
		let ids = [];
		e.detail.index?.map((i) => {
			ids.push(taskInfo.value.list[i]?.id);
		});
		formData.detachIds = ids;
	} else {
		formData.detachIds = [];
	}
}

// 表单规则定义
const rules = ref({
	detachStatus: {
		type: 'string',
		required: true,
		message: '请选择拆卸状态',
		trigger: ['change']
	}
});

// 获取扫码结果
function getScanResult(result: any) {
	resetData();
	if (result) {
		getDeviceInfo(result);
	}
}

// form信息重置
const tableRef = ref();
function resetData() {
	taskInfo.value = {};
	formData.consumeCode = '';
	formData.detachStatus = null;
	formData.detachIds = [];
	formData.detachIndexs = [];
	tableRef.value && tableRef.value.clearSelection();
	uni.pageScrollTo({
	    scrollTop: 0,
	    duration: 100
	})
}

// 重置表单信息 & 光标自动blur
const scanBarRef = ref();
const datekey = ref(new Date());
function resetFields() {
	resetData();
	// uForm.value.resetFields();
	scanBarRef.value && scanBarRef.value.reset();
	datekey.value = new Date();
}

// 校验提交
const uForm = ref();
const postLoading = ref(false);
function submit() {
	if (!taskInfo.value.consumeCode) {
		uni.showToast({
			title: '请录入耗材编号',
			icon: 'none'
		});
		return false;
	}
	if (!formData.detachIds.length) {
		uni.showToast({
			title: '请选择耗材',
			icon: 'none'
		});
		return false;
	}
	uForm.value.validate().then(async () => {
		postLoading.value = true;
		const result: any = await http({
			method: 'POST',
			url: `/eam/csmmaterialdata/updateMaterialList`,
			data: {
				ids: formData.detachIds,
				// consumeCode: taskInfo.value.consumeCode,
				status: formData.detachStatus,
				// id: taskInfo.value.id,
			}
		}).finally(() => {
			postLoading.value = false;
		});

		uni.showToast({
			title: '提交成功'
		});
		setTimeout(() => {
			postLoading.value = false;
			resetFields();
		}, 1000);
	});
}

// 获取耗材信息（接口请求）
async function getDeviceInfo(consumeCode: string) {
	loading.value = true;
	http({
		method: 'GET',
		url: `/eam/csmmaterialdata/getRecordList/${consumeCode}`,
		data: {}
	}).catch(()=>{
		loading.value = false;
		resetFields();
	}).then((data:any)=>{
		if (data?.data) {
			taskInfo.value = {
				...data?.data,
				consumeCode
			};
		}
		loading.value = false;
	});
	// 使用测试数据--预留，调试时使用
	// setTimeout(() => {
	// 	loading.value = false;
	// 	taskInfo.value = mockData;
	// }, 1000);
}
</script>

<style lang="scss" scoped>
.handle-ok {
	min-width: 75px;
	color: #19be6b;
}
.card {
	background-color: #fff;
	margin: 10px 10px;
	border-radius: 8px;
	padding: 8px 12px;
	transition: all 300ms ease;
	box-shadow: 0 2px 6px rgba(3, 121, 255, 0.05);
}

.overhidden {
	overflow: hidden;
}

.uni-table-th {
	font-size: 14px;
	font-weight: 400;
	color: #16254e;
}

uni-page-body {
	min-height: 100vh;
	height: 100%;
	background-color: #fbfbff;
}

.u-divider {
	margin: 10px 0;
}

.baseForm {
	background-color: #fbfbff;
	display: block;
	min-height: 100vh;
}

.title {
	font-size: 16px;
	margin: 6px 0 14px;
	font-weight: bold;
	.u-icon {
		margin-right: 3px;
	}
}

.submit_btn {
	margin: 0px 20rpx 20rpx 10rpx;
}
.grey_btn {
	margin: 0px 10rpx 20rpx 20rpx;
	height: 45px;
	line-height: 45px;
}
.submit_btn_div {
	position: fixed;
	display: flex;
	align-items: center;
	width: 100%;
	bottom: 0;
	z-index: 10;
	uni-button {
		flex: 1;
		border-radius: 10px;
	}
}

:deep(.u-form-item__body) {
	padding: 4px 0 12px;
}

.mt-10- {
	margin-top: -30px;
}

.unitable {
	width: calc(100% - 20px);
	margin: 0 10px 70px;
	box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
	border-radius: 4px;
}
</style>
